

#include"head.h"
struct filedata
{
    char name[32];
    int size;
    char str[512];
    int flag;
};
int main()
{
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        perror("socket error");
        return -1;
    }

    struct sockaddr_in myaddr;
    myaddr.sin_family       = AF_INET;
    myaddr.sin_port         = htons(8888);
    myaddr.sin_addr.s_addr  = inet_addr("172.16.3.46");
    socklen_t len =sizeof(struct sockaddr_in);

    struct sockaddr_in dstaddr;


    int ret = bind(sockfd,(struct sockaddr*)&myaddr,len);
    if(ret < 0)
    {
        perror("bind");
        return -1;
    }

    struct filedata data;
    //data.str = (char*)malloc(sizeof(char)*(data.size));
    int i = 0;
    while(1)
    {
        bzero(&data,sizeof(data));
        char buff[1024] = {0};
        if( i== 0 ){
            printf("等待接收文件\n");
            i++;
        } 
        ret = recvfrom(sockfd,&data,sizeof(struct filedata),0,(struct sockaddr*)&dstaddr,&len);
        if(ret < 0)
        {
            perror("recvfrom");
            return -1;
        }
        //printf("正在接收文件:%s\n",data.name);
        //printf("name =%s size =%d\n",data.name,data.size);
        FILE *fp = NULL;
        if(data.flag == 0)     fp = fopen(data.name,"w+");
        else if(data.flag == 1) fp =fopen(data.name,"a+");

        int re = fwrite(data.str,data.size,sizeof(char),fp);
        fclose(fp);
        if(data.size == 0)
        {
            printf("文件接收完毕\n");
            i = 0;
            sendto(sockfd,"q",1,0,(struct sockaddr*)&dstaddr,len);
        }
    }
close(sockfd);
}
